# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import time
from tortoise.expressions import Q
from hypertext import PagingResult
from common.models.draws import DrawsPromptCategoryModel
from common.models.draws import DrawsPromptLexiconModel
from apps.admin.schemas.apply.draws import prompt_lexicon_schema as schema


class DrawsPromptLexiconService:
    """ 绘画提示词词汇服务类 """

    @classmethod
    async def lists(cls, params: schema.DrawsPromptLexiconSearchIn) -> PagingResult[schema.DrawsPromptLexiconVo]:
        """
        提示词词汇列表

        Args:
            params (schema.DrawsPromptLexiconSearchIn): 搜索参数

        Returns:
            PagingResult[schema.DrawsPromptLexiconVo]

        Author:
            zero
        """
        where = DrawsPromptLexiconModel.build_search({
            "=": ["is_disable"],
            "%like%": ["prompt"],
            "datetime": ["start_time|end_time@create_time"]
        }, params.__dict__)

        where.append(Q(engine=params.engine))
        where.append(Q(is_delete=0))

        _model = DrawsPromptLexiconModel.filter(is_delete=0).filter(*where).order_by("-sort", "-id")
        _pager = await DrawsPromptLexiconModel.paginate(
            model=_model,
            page_no=params.page_no,
            page_size=params.page_size,
            fields=DrawsPromptLexiconModel.without_field("is_delete,delete_time")
        )

        # 所属用户
        cate_ids = [item["category_id"] for item in _pager.lists]
        category: dict = await DrawsPromptCategoryModel.queryCateDictsById(cate_ids)

        _lists = []
        for item in _pager.lists:
            _lists.append(schema.DrawsPromptLexiconVo(
                id=item["id"],
                engine=item["engine"],
                category_id=item["category_id"],
                category=category.get(item["category_id"], "-"),
                prompt=item["prompt"],
                prompt_en=item["prompt_en"],
                sort=item["sort"],
                is_disable=item["is_disable"],
                create_time=item["create_time"]

            ))

        _pager.lists = _lists
        return _pager

    @classmethod
    async def add(cls, post: schema.DrawsPromptLexiconAddIn) -> None:
        """
        提示词词汇新增

        Args:
            post (schema.DrawsPromptLexiconAddIn): 新增参数

        Author:
            zero
        """
        lists = []
        keywords = post.content.split("\n")
        for item in keywords:
            array = item.split("&")
            if len(array) < 2:
                continue
            lists.append(DrawsPromptLexiconModel(
                engine=post.engine,
                category_id=post.category_id,
                prompt=array[0].strip(),
                prompt_en=array[1].strip(),
                sort=post.sort,
                is_disable=post.is_disable,
                create_time=int(time.time()),
                update_time=int(time.time())
            ))

        if lists:
            await DrawsPromptLexiconModel.bulk_create(lists)

    @classmethod
    async def edit(cls, post: schema.DrawsPromptLexiconEditIn) -> None:
        """
        提示词词汇编辑

        Args:
            post (schema.DrawsPromptLexiconEditIn): 编辑参数

        Author:
            zero
        """
        await DrawsPromptLexiconModel.filter(id=post.id).get()
        await DrawsPromptLexiconModel.filter(id=post.id).update(
            prompt=post.prompt,
            prompt_en=post.prompt_en,
            sort=post.sort,
            is_disable=post.is_disable,
            update_time=int(time.time())
        )

    @classmethod
    async def delete(cls, id_: int) -> None:
        """
        提示词词汇删除

        Args:
            id_ (int): ID

        Author:
            zero
        """
        await DrawsPromptLexiconModel.filter(id=id_).get()
        await DrawsPromptLexiconModel.filter(id=id_).update(
            is_delete=1,
            delete_time=int(time.time())
        )
